<template>
  <div class="dialog-wrap">
    <div class="dialog-header f-r-cc">
      <p class="title">{{ type == 1 ? '个体工商户入驻申请' : '企业/公司入驻申请' }}</p>
    </div>
    <div class="dialog-content">
      <el-form
        ref="formRef"
        style="width: 100%"
        :model="ruleForm"
        :rules="rules"
        label-width="120"
        label-position="top"
        :hide-required-asterisk="true"
      >
        <el-row :gutter="32">
          <el-col :xs="24" :sm="12" :md="12" :lg="12">
            <el-form-item label="商户名称" prop="mer_name">
              <el-input v-model="ruleForm.mer_name" placeholder="请输入商户名称" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12">
            <el-form-item :label="type == 1 ? '经营者姓名' : '法人姓名'" prop="name">
              <el-input v-model="ruleForm.name" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12">
            <el-form-item :label="type == 1 ? '经营者手机号' : '法人手机号'" prop="phone">
              <el-input v-model="ruleForm.phone" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12">
            <el-form-item label="验证码" prop="code">
              <el-input v-model="ruleForm.code">
                <template #suffix>
                  <span class="code-suffix-text cursor" @click.stop="getCodeBefore">{{
                    sms_info.codeDisabled ? sms_info.countdownText : '获取验证码'
                  }}</span>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12">
            <el-form-item label="商户分类" prop="mer_type_id">
              <el-select v-model="ruleForm.mer_type_id" placeholder="请选择" size="large">
                <el-option
                  v-for="item in category_type__list"
                  :key="item.merchant_category_id"
                  :label="item.category_name"
                  :value="item.merchant_category_id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12">
            <el-form-item label="店铺类型" prop="merchant_category_id">
              <el-select v-model="ruleForm.merchant_category_id" placeholder="请选择" size="large">
                <el-option
                  v-for="item in store_type_list"
                  :key="item.mer_type_id"
                  :label="item.type_name"
                  :value="item.mer_type_id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12">
            <el-form-item label="营业执照(图片支持png，jpg，jpeg)" prop="business_license">
              <el-upload
                class="avatar-uploader f-r-cc"
                :action="uploadPath"
                :show-file-list="false"
                accept="image/*"
                :data="{ server: 1 }"
                :headers="headers"
                name="file"
                :on-success="handleSuccess"
                :on-change="uploadChange"
                :before-upload="uploadBefore"
              >
                <template #trigger>
                  <div
                    class="upload-icon-wrap f-c-cc"
                    v-if="ruleForm.business_license"
                    @click="uploadImg('business_license')"
                  >
                    <img :src="$imgUrl(ruleForm.business_license)" alt="" class="upload-img" />
                  </div>
                  <div
                    class="upload-icon-wrap f-c-cc"
                    v-else
                    @click="uploadImg('business_license')"
                  >
                    <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
                  </div>
                </template>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" v-if="type == 2">
            <el-form-item label="法人身份证正面照(图片支持png，jpg，jpeg)" prop="front_of_ID_card">
              <el-upload
                class="avatar-uploader f-r-cc"
                :action="uploadPath"
                :show-file-list="false"
                accept="image/*"
                :data="{ server: 1 }"
                :headers="headers"
                name="file"
                :on-success="handleSuccess"
                :on-change="uploadChange"
                :before-upload="uploadBefore"
              >
                <template #trigger>
                  <div
                    class="upload-icon-wrap f-c-cc"
                    v-if="ruleForm.front_of_ID_card"
                    @click="uploadImg('front_of_ID_card')"
                  >
                    <img :src="$imgUrl(ruleForm.front_of_ID_card)" alt="" class="upload-img" />
                  </div>
                  <div
                    class="upload-icon-wrap f-c-cc"
                    v-else
                    @click="uploadImg('front_of_ID_card')"
                  >
                    <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
                  </div>
                </template>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" v-if="type == 2">
            <el-form-item
              label="法人身份证反面照(图片支持png，jpg，jpeg)"
              prop="reverse_of_ID_card"
            >
              <el-upload
                class="avatar-uploader f-r-cc"
                :action="uploadPath"
                :show-file-list="false"
                accept="image/*"
                :data="{ server: 1 }"
                :headers="headers"
                name="file"
                :on-success="handleSuccess"
                :on-change="uploadChange"
                :before-upload="uploadBefore"
              >
                <template #trigger>
                  <div
                    class="upload-icon-wrap f-c-cc"
                    v-if="ruleForm.reverse_of_ID_card"
                    @click="uploadImg('reverse_of_ID_card')"
                  >
                    <img :src="$imgUrl(ruleForm.reverse_of_ID_card)" alt="" class="upload-img" />
                  </div>
                  <div
                    class="upload-icon-wrap f-c-cc"
                    v-else
                    @click="uploadImg('reverse_of_ID_card')"
                  >
                    <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
                  </div>
                </template>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div class="check-box f-r-dc">
        <div class="check-icon f-r-cc" :class="checked ? 'active' : ''" @click="checkChange">
          <div class="icon"></div>
        </div>
        <div class="check-ctn f-r-dc">
          <span class="cursor" @click="checkChange">已阅读并同意</span>
          <span class="text-active cursor" @click="toAgreement">《商户入驻协议》</span>
        </div>
      </div>
    </div>
    <div class="dialog-footer f-c-cc">
      <div @click="cancel" class="dialog-footer-cancel f-r-cc cursor">取消</div>
      <div type="primary" @click="submit" class="dialog-footer-confirm f-r-cc cursor">提交</div>
    </div>
  </div>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import { getMerchantType, getMerchantCategory, apply, send } from '@/api/index'
import clickCaptcha from '@/components/clickCaptcha'
import { uuid } from '@/utils/random'
import { useUser } from '@/stores/user'
const user_store = useUser()

const router = useRouter()
const route = useRoute()

// const props = defineProps({
//   type: {
//     type: Number,
//     default: 1
//   }
// })

const type = ref(route.query.type)

const dialogVisible = ref(false)

const checked = ref(false)

const uploading = ref(false)

const formRef = ref()

const current_upload_name = ref('business_license')

const uploadPath = `${import.meta.env.VITE_API_URL}/upload/file`

const headers = {
  Authorization: 'Bearer ' + localStorage.getItem('token')
}

const sms_info = ref({
  codeDisabled: false,
  countdownText: '获取验证码',
  timer: null,
  currentTime: 60
})

const ruleForm = ref({
  mer_name: '',
  name: '',
  phone: '',
  code: '',
  mer_type_id: '',
  merchant_category_id: '',
  business_license: '',
  front_of_ID_card: '',
  reverse_of_ID_card: ''
})

const captcha_value = ref('')

const rules = ref({
  mer_name: [{ required: true, message: '请输入商户名称', trigger: 'blur' }],
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  code: [{ required: true, message: '请输入验证码', trigger: 'blur' }],
  mer_type_id: [{ required: true, message: '请选择分类', trigger: 'change' }],
  merchant_category_id: [{ required: true, message: '请选择类型', trigger: 'change' }],
  business_license: [{ required: true, message: '请上传营业执照', trigger: 'change' }],
  front_of_ID_card: [{ required: true, message: '请上传法人身份证正面照', trigger: 'change' }],
  reverse_of_ID_card: [{ required: true, message: '请上传法人身份证反面照', trigger: 'change' }]
})

// 协议
function toAgreement(name) {
  router.push({ name: 'Agreement', query: { type: 'settlement_agreement' } })
}

function uploadImg(name) {
  current_upload_name.value = name
}

function checkChange() {
  checked.value = !checked.value
}

function showDialog() {
  dialogVisible.value = true
}

function countdown() {
  sms_info.value.codeDisabled = true
  sms_info.value.timer = setInterval(() => {
    sms_info.value.currentTime -= 1
    sms_info.value.countdownText = `${sms_info.value.currentTime} S`
    if (sms_info.value.currentTime <= 0) {
      clearInterval(sms_info.value.timer)
      sms_info.value.currentTime = 60
      sms_info.value.codeDisabled = false
    }
  }, 1000)
}

async function getCode() {
  let res = await send({
    captchaId: user_store.captchaId,
    mobile: ruleForm.value.phone,
    captchaInfo: captcha_value.value,
    template_code: 'SMS_468345255'
  })
  if (res.code && res.code == 1) {
    ElMessage.success(res.msg || '验证码发送成功')
    countdown()
  }
}

function onSubmit(captchaInfo) {
  captcha_value.value = captchaInfo.captchaInfo
  if (captchaInfo && captchaInfo.code && captchaInfo.code == 1) {
    // 校验成功
    getCode()
  } else {
    ElMessage.error(captchaInfo.msg)
  }
}

function getCodeBefore() {
  if (sms_info.value.codeDisabled) return
  if (!ruleForm.value.phone) {
    ElMessage.info('请输入手机号')
    return
  }
  let uuid_ = uuid()
  clickCaptcha(uuid_, (captchaInfo) => onSubmit(captchaInfo))
}

function handleSuccess(res) {
  ruleForm.value[current_upload_name.value] = res.data.path
}
async function uploadBefore() {
  if (uploading.value) return
}

function uploadChange(res) {
  uploading.value = true
  if (res.status === 'success') {
    uploading.value = false
  }
  if (res.status === 'fail') {
    ElMessage.error({ message: '上传失败' })
    uploading.value = false
  }
}

const store_type_list = ref([])
const category_type__list = ref([])

// 获取店铺类型列表
async function getMerchantTypeData() {
  let res = await getMerchantType({})
  store_type_list.value = res.data
}

// 获取商户类型列表
async function getMerchantCategoryData() {
  let res = await getMerchantCategory({})
  category_type__list.value = res.data
}

function cancel () {
    router.back()
}

async function submit() {
  if (!checked.value) {
    ElMessage.info('请先阅读并同意协议')
    return
  }
  await formRef.value.validate(async (valid, fields) => {
    if (valid) {
      let params = {
        mer_name: '',
        name: '',
        phone: '',
        code: '',
        mer_type_id: '',
        merchant_category_id: ''
      }
      for (let key in params) {
        params[key] = ruleForm.value[key]
      }
      let { business_license, front_of_ID_card, reverse_of_ID_card } = ruleForm.value
      if (type.value == 1) {
        params.images = [business_license]
      } else {
        params.images = [business_license, front_of_ID_card, reverse_of_ID_card]
      }
      let res = await apply(params)
      if (res.code && res.code == 0) {
        ElMessage.info(res.msg)
        return
      }
      ElMessage.success('提交成功')
      dialogVisible.value = false
    }
  })
}

onMounted(() => {
  getMerchantTypeData()
  getMerchantCategoryData()
})

defineExpose({
  showDialog
})
</script>
<style scoped lang="less">
@import './index.less';
</style>
